Installation

pip install reverse_geocoder

OR

pip install --upgrade reverse_geocoder

Import Library


In [32]:
import reverse_geocoder as rg

Geocoding a Single Coordinate


In [33]:
import pprint
pp = pprint.PrettyPrinter(indent=4)
coordinate = (51.520328, -0.097712)

In [34]:
result = rg.get(coordinate) # default mode = 2

In [35]:
pp.pprint(result)


{   'admin1': 'England',
    'admin2': 'Greater London',
    'cc': 'GB',
    'lat': '51.51988',
    'lon': '-0.09446',
    'name': 'Barbican'}

Geocoding Multiple Coordinates


In [36]:
coordinates = (51.5214588,-0.1729636),(9.936033, 76.259952),(37.38605,-122.08385)

In [37]:
results = rg.search(coordinates) # default mode = 2

In [38]:
pp.pprint(results)


[   {   'admin1': 'England',
        'admin2': 'Greater London',
        'cc': 'GB',
        'lat': '51.51116',
        'lon': '-0.18426',
        'name': 'Bayswater'},
    {   'admin1': 'Kerala',
        'admin2': 'Ernakulam',
        'cc': 'IN',
        'lat': '9.93988',
        'lon': '76.26022',
        'name': 'Cochin'},
    {   'admin1': 'California',
        'admin2': 'Santa Clara County',
        'cc': 'US',
        'lat': '37.38605',
        'lon': '-122.08385',
        'name': 'Mountain View'}]

Single Process Geocoding


In [39]:
coordinates = (51.459185, -2.585109),(1.292697, 103.852033),(-27.450283, 153.016957)

In [40]:
results_slow = rg.search(coordinates,mode=1)

In [41]:
pp.pprint(results_slow)


[   {   'admin1': 'England',
        'admin2': 'Bristol',
        'cc': 'GB',
        'lat': '51.45523',
        'lon': '-2.59665',
        'name': 'Bristol'},
    {   'admin1': '',
        'admin2': '',
        'cc': 'SG',
        'lat': '1.28967',
        'lon': '103.85007',
        'name': 'Singapore'},
    {   'admin1': 'Queensland',
        'admin2': 'Brisbane',
        'cc': 'AU',
        'lat': '-27.46141',
        'lon': '153.02311',
        'name': 'Spring Hill'}]

Geocoding from an Input File


In [42]:
import csv
input_filename = '/Users/ajay/Workspace/pydata_demo/coordinates_10000.csv'
output_filename = '/Users/ajay/Workspace/pydata_demo/coordinates_10000_geocoded.csv'
cities = [(row[0],row[1]) for row in csv.reader(open(input_filename,'rt'),delimiter='\t')]

In [43]:
pp.pprint(cities[0:5])


[   ('13.9280531', '100.3735803'),
    ('13.7233157', '-89.1415332'),
    ('28.6440457', '-81.122403'),
    ('35.9105783', '128.817739'),
    ('43.2615353', '-2.9267777')]

In [44]:
results = rg.search(cities)

In [45]:
rows = []
for idx, city in enumerate(cities):
    write_row = []
    lat = city[0]
    lon = city[1]
    gdata = results[idx]
    rows.append([lat,lon,gdata['name'],gdata['admin1'],gdata['admin2'],gdata['cc']])
csvwriter = csv.writer(open(output_filename,'wt'),delimiter='\t')
csvwriter.writerows(rows)

In [45]: